package com.itheima.service;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * @author tongchen
 * @create 2022-12-01 10:48
 */
public class UserService {
    SqlSessionFactory sqlSessionFactory;
    public User select (String username ,String password){
        //1.创建工厂
        sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        //创建session
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        User user = mapper.select(username, password);
        //释放资源
        sqlSession.close();
        return user;
    }
    //注册功能
    public boolean register(User user){
        //1.创建工厂
        sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        //创建session
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //创建mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        User user1 = mapper.selectByUsername(user.getUsername());
        if(user1==null){
            //需要注册
            mapper.add(user);
            sqlSession.commit();
            sqlSession.close();
        }
        return user1==null;
    }

}
